<?php

/*
采购订单列表
*/
namespace Modules\Purchasing\Http\Repositories;


use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Modules\Purchasing\Models\Provisional;
use Modules\Purchasing\Models\Provisionalschedule;
use Illuminate\Support\Facades\DB;
use Catch\Exceptions\FailedException;
use Modules\Base\Service\BoxService;
use Modules\Purchasing\Models\Supplier;
use Modules\Purchasing\Models\Supplierschedule;
use Modules\Purchasing\Models\Purchaseorder;
use Modules\Purchasing\Models\Purchaseorderschedule;
use Modules\Warehouse\Models\Storagelocation;
use Modules\Purchasing\Models\Inspectionlist;
use Modules\Purchasing\Models\Inspectionlisttable;


class ProvisionalReget
{
    
    /*
    数据列表
    */
    public static function list($data = [])
    {
        return self::getBuilder($data)->paginate($data['per_page'] ?? 20);
    }

     /**
     *查询列表
     *
     * @param array $data
     * @return Builder
     */
    public static function getBuilder(array $data = []): Builder
    {
       
        $builder = Provisional::query()->with('detailscheckAll');
        if (isset($data['ordernumber'])) {
            $builder->where('ordernumber', 'like', "%{$data['ordernumber']}%");
        }

        
        if (isset($data['ProvisionalOrder'])) {
            $builder->where('ProvisionalOrder', 'like', "%{$data['ProvisionalOrder']}%");
        }
        if (isset($data['remarks'])) {
            $builder->where('remarks', 'like', "%{$data['remarks']}%");
        }

        if (isset($data['state'])) {
            $builder->where('state',$data['state']);
        }

        if (isset($data['fbillno'])) {
            $purchaseorder = purchaseorder::select('fbillno','id','fpurchaseorgid_number','fpurchaseorgid_name')->where('fbillno', 'like', "%{$data['fbillno']}%")->get()->toArray();
                foreach ($purchaseorder as $k=>$v){
                    $purchaseorder_id[] = $v['id'];
                }
                 $purchaseorder_id = array_unique($purchaseorder_id);
            $Provisionalschedule = Provisionalschedule::select('provisional_id')->whereIn('purchaseorder_id',$purchaseorder_id)->get()->toArray();
            foreach ($Provisionalschedule as $k=>$v){
                $provisional_id[] = $v['provisional_id'];
            }
            $provisional_id = array_unique($provisional_id);
            $builder->whereIn('id',$provisional_id);
        }
        
        //查物料编码 
        if (isset($data['fmaterialid'])) {

            $fmaterialid = Purchaseorderschedule::select('fmaterialid','id')->where('remarks', 'like', "%{$data['fmaterialid']}%")->get()->toArray();
            $fmaterial_id = [];
            foreach($fmaterialid as $k=>$v){
                $fmaterial_id[] = $v['id'];
            }
            $fmaterial_id = array_unique($fmaterial_id);
            $Provisionalschedule = Provisionalschedule::select('purchaseorderschedule_id','provisional_id')
            ->whereIn('purchaseorderschedule_id',$fmaterial_id)
            ->get()
            ->toArray();

            $provisional_id = [];
            foreach($Provisionalschedule as $k=>$v){
                $provisional_id[] = $v['provisional_id'];
            }
            $provisional_id = array_unique($provisional_id);
            $builder->whereIn('id',$provisional_id);
        }

        $builder->orderBy('id', 'desc');
        return $builder;
    }

    /*
    数据添加方法
    */
    public static function create(array $data)
    {
        
        $Provisional = new Provisional;
        return self::createOrSave($Provisional, $data);
    }

    //数据添加方法
    public static function createOrSave(Provisional $Provisional,$data)
    {
        // return throw new FailedException('技术在处理问题，亲！停止暂收！');
        // exit;
        
        if(empty($data['detailscheck_all']))throw new FailedException('提交数据不能为空！');
        
        $purchaseorder_id = '';
        foreach($data['detailscheck_all'] as $k=>$v){
            $supplier_id = Supplier::where('id',$v['supplier_id'])->where('state',0)->first();
            if(!empty($supplier_id)){
                throw new FailedException('亲！送货单未审核无法暂收。');
            }
            $barcode  = Provisionalschedule::where('barcode',$v['barcode'])->first();
            if(!empty($barcode)){
                throw new FailedException('亲！有条码数据已暂收不能重复暂收。');
            }

            //判断是否是同一个供应商
           $purchaseorder_id = Purchaseorder::select('fsupplierid_number')->where('id',$v['purchaseorder_id'])->first();
           if(!empty($purchaseorder_id)){
                $purchaseorder_id .= trim($purchaseorder_id['fsupplierid_number']).'、';
           }
            // $purchaseorder_id[$v['purchaseorder_id']] = $v['purchaseorder_id'];
        }
        
        $explode = explode('、',$purchaseorder_id);
        $explode = array_unique($explode);
        // if(count($explode) > 1)throw new FailedException('亲！暂收单必须同一个供应商');

        //获取总的箱号数
        // $countnumber = Supplierschedule::select(DB::raw('SUM(number) as number'))
        // ->where('supplier_id',$data['detailscheck_all'][0]['supplier_id'])
        // ->groupby(['supplier_id'])->first();
        // if(count($data['detailscheck_all']) != $countnumber->number) throw new FailedException('亲！箱数未暂收完');

        //实际到货箱数
        $countnumber = Supplierschedule::select(DB::raw('SUM(actual_number) as actual_number'))
        ->where('supplier_id',$data['detailscheck_all'][0]['supplier_id'])
        ->groupby(['supplier_id'])->first();
        if(count($data['detailscheck_all']) != $countnumber->actual_number) throw new FailedException('亲！箱数未暂收完');

        try {
            //开始起事务
            DB::beginTransaction();

            $ProvisionalData = [];
            // $ProvisionalData['ordernumber'] = 'ZSD'.date('Ymd',time()).makeSerial();
            $ProvisionalData['ordernumber'] =  \App\Services\UnitService::createDocno(\App\Enums\OrderNoPrefix::NO_ZSD->value);

            $ProvisionalData['remarks'] = $data['remarks'];
            $ProvisionalData['creator_id'] = $data['creator_id'];
            $Provisional->fill($ProvisionalData);
            $Provisional->save();

            // $data['detailscheck_all'] = [
            //     [
            //         'supplierschedule_id'=>['3','4'],
            //         'quantityreceived'=>'5555',
            //         'barcode'=>'25555555',
            //         'storagelocation'=>1,
            //     ],
            //     [
            //         'supplierschedule_id'=>['3','4'],
            //         'quantityreceived'=>'5555',
            //         'barcode'=>'25555555',
            //         'storagelocation'=>1,
            //      ]
            // ];
            $Provisional->detailscheckAll()->createMany( $data['detailscheck_all'] );

            //生成检验单
            $resdata = Provisional::query()->where('id',$Provisional['id'])->with('detailscheckAll')->first()->toArray();
            // $Inspectionlist['inspectionnumber'] = 'LLJY'.date('Ymd',time()).makeSerial();
            $Inspectionlist['inspectionnumber'] = \App\Services\UnitService::createDocno(\App\Enums\OrderNoPrefix::NO_LLJY->value);
           
            $Inspectionlist['created_at'] = time();
            $insertGetId = Inspectionlisttable::insertGetId($Inspectionlist);
            if(empty($insertGetId)){
                return  throw new FailedException('亲！数据录入异常');
            }
            foreach($resdata['detailscheck_all'] as $k=>$v){
                $Provisionalschedule = Provisionalschedule::query()->updateOrInsert(['id' => $v['id']], [
                        'inspectionlisttable_id'=>$insertGetId,
                    ]); 
                    if(empty($Provisionalschedule)){
                        return  throw new FailedException('亲！数据录入异常');
                    }

                    //修改成功送货单状态为暂收
                    $supplierOrder = Supplier::select('id')->where('id',$v['supplier_id'])->update(['temporary'=>1]);
            }
            DB::commit();
            return $data=['code'=>1000,'message'=>'添加成功'];

        } catch (\Exception $e) {
            DB::rollBack();
            throw new FailedException('数据添加失败，服务器上火星了请联系技术处理');
        }

    }

    //修改
    public static function createUpdate($id,$data)
    {
        
        try {
            //开始起事务
            DB::beginTransaction();
            $Provisional = Provisional::query()->updateOrCreate(['id' => $id], [
                'modifier'       => $data['modifier']  ?? '',
                'remarks'       => $data['remarks']  ?? '',
            ]);
            Provisionalschedule::where('provisional_id',$id)->delete();
            $Provisional->detailscheckAll()->createMany($data['detailscheckAll']);          
            DB::commit();
            return '修改成功';
        } catch (\Exception $e) {
            DB::rollBack();
            throw new FailedException('数据修改失败，服务器上火星了请联系技术处理');
        }

    }

    /**
     * 查询一条数据
     *
     */
    public static function find($id)
    {
        return Provisional::query()->with('detailscheckAll')->find($id);
    }

    /**
     * @param $id
     * @return void
     */
    public static function delete($id)
    {
       
        try {
            //开始起事务
            DB::beginTransaction();
            $inspectionlisttable = Provisionalschedule::select('inspectionlisttable_id','inspectionlist_id')->where('provisional_id',$id)->get()->toArray();
            $inspectionlisttable_id = [];
            $inspectionlist_id = [];
            foreach($inspectionlisttable as $k=>$v){
                $inspectionlisttable_id[]=$v['inspectionlisttable_id'];
                $inspectionlist_id[]=$v['inspectionlist_id'];
                
            }
            Provisional::query()->where('id',$id)->delete();
            Provisionalschedule::query()->where('provisional_id',$id)->delete();

            Inspectionlisttable::query()->whereIn('id',$inspectionlisttable_id)->delete();
            Inspectionlist::query()->whereIn('id',$inspectionlist_id)->delete();
            DB::commit();
            return '删除成功';
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }


    }
     /**暂收审核
     * @param $id
     * @return void
     */
    public static function auditupdate($id)
    {
       
        try {
            //开始起事务
            DB::beginTransaction();

            $resdata = Provisionalschedule::select('id','provisional_id')->where('provisional_id',$id)->get();

            foreach($resdata as $k=>$v){
                $Inspectionlist = [];
                $Inspectionlist['inspectionnumber'] = 'LLJY'.date('Ymd',time()).makeSerial();
                $Inspectionlist = Inspectionlist::insertGetId($Inspectionlist);
                Provisionalschedule::query()->updateOrInsert(['id' => $v['id']], [
                    'inspectionlist_id'=>$Inspectionlist,
                ]); 
                Provisional::query()->updateOrCreate(['id' => $v['provisional_id']], [
                    'state' => 1,
                ]);   
            }

            DB::commit();
            return '审核成功';
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }

    }


    /**
     * @param $id
     * @return void
     */
    public static function showApi($datares)
    {
   
            foreach($datares as $k=>$v){
                
                $inspectionlist_id = Inspectionlist::where('id',$v['inspectionlisttable_id'])->first();
                
                if(!empty($inspectionlist_id)){
                     $datares[$k]['inspectionnumber'] = $inspectionlist_id->inspectionnumber;
                }else {
                    $datares[$k]['inspectionnumber'] = '';
                }
                
                $data = Supplierschedule::
                select('supplier_id','purchaseorder_id',DB::raw('SUM(quantity) as quantity'),'purchaseorderschedule_id')
                ->where('id',$v['supplierschedule_id'])
                ->groupby(['supplier_id','purchaseorder_id','purchaseorderschedule_id']) 
                ->get();
 
                foreach($data as $ks=>$vs){  
                    $supplierOrder = Supplier::select('supplierOrder')->where('id',$vs['supplier_id'])->first();

                    $datares[$k]['supplierOrder'] = $supplierOrder['supplierOrder'];//送货单号


                    $fbillno = Purchaseorder::select('fbillno','fsupplierid_number','fsupplierid_name')->where('id',$vs['purchaseorder_id'])->first();
                    $datares[$k]['fbillno'] = $fbillno['fbillno'];//采购订单号
                    $datares[$k]['fsupplierid_number'] = $fbillno['fsupplierid_number'];
                    $datares[$k]['fsupplierid_name'] = $fbillno['fsupplierid_name'];
                       
                    $Purchaseorderschedule = Purchaseorderschedule::select(
                        'fseq','fentryid','fmaterialid',
                        'fmaterialname','fmaterialmodel',
                        'fmodel','funitid_number','funitid_name',
                        'funitid_name','fqty','fdeliverydate',
                        'fmemo'
                    )
                    ->where('id',$vs['purchaseorderschedule_id'])->first();
                    
           
                    $datares[$k]['fseq'] = $Purchaseorderschedule['fseq'];
                    $datares[$k]['fentryid'] = $Purchaseorderschedule['fentryid'];
                    $datares[$k]['fmaterialid'] = $Purchaseorderschedule['fmaterialid'];
                    $datares[$k]['fmaterialname'] = $Purchaseorderschedule['fmaterialname'];
                    $datares[$k]['fmaterialmodel'] = $Purchaseorderschedule['fmaterialmodel'];
                    $datares[$k]['fmodel'] = $Purchaseorderschedule['fmodel'];
                    $datares[$k]['funitid_number'] = $Purchaseorderschedule['funitid_number'];
                    
                    $datares[$k]['funitid_name'] = $Purchaseorderschedule['funitid_name'];
                    $datares[$k]['fqty'] = $Purchaseorderschedule['fqty'];
                    $datares[$k]['fdeliverydate'] = $Purchaseorderschedule['fdeliverydate'];
                    $datares[$k]['fmemo'] = $Purchaseorderschedule['fmemo'];

                    $storagelocation = Db::table('storagelocation')->select('repositoryname')->where('id','=',$v['storagelocation'])->first();
                    if(!empty($storagelocation)){
                        $datares[$k]['repositoryname'] = $storagelocation->repositoryname; 
                    }else{
                        $datares[$k]['repositoryname'] = ''; 
                    }
                    
                 
                }
            }
            
            return $datares;
    }




}
